<template>
  <div v-loading="loading" class="sp-page-main">
    <!-- filter start -->
    <el-form ref="filterForm" :inline="true" :model="filterForm" label-width="110px" size="small">

      <el-form-item
        prop="name"
        label="服务商名称："
      >
        <el-input
          ref="filterFormInput"
          v-model="filterForm.name"
          placeholder="请输入"
          clearable
          class="app-w-350"
          @keyup.enter.native="submitFilterForm"
        />
      </el-form-item>
      <el-form-item
        prop="serial"
        label="服务商编号："
      >
        <el-input
          v-model="filterForm.serial"
          placeholder="请输入"
          clearable
          class="app-w-350"
          @keyup.enter.native="submitFilterForm"
        />
      </el-form-item>
      <el-form-item
        prop="userSuffix"
        label="登录账号："
      >
        <el-input
          v-model="filterForm.userSuffix"
          placeholder="请输入"
          clearable
          class="app-w-350"
          @keyup.enter.native="submitFilterForm"
        />
      </el-form-item>

      <el-form-item
        prop="spPackageId"
        label="服务商权限组："
      >
        <el-select v-model="filterForm.spPackageId" filterable placeholder="可通过名称搜索" class="app-w-350" clearable>
          <el-option label="全部权限组" value />
          <el-option v-for="item in spPackageOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item
        prop="tags"
        label="标签："
      >
        <el-select
          v-model="filterForm.tags"
          filterable
          multiple
          collapse-tags
          placeholder="可通过名称搜索"
          class="app-w-350"
          clearable
          @change="(val)=>selectMultipleChange(val,'tags')"
        >
          <el-option label="全部标签" value />
          <el-option
            v-for="item in tagOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        prop="creator"
        label="业务人员："
      >
        <el-select
          v-model="filterForm.creator"
          filterable
          placeholder="可通过名称搜索"
          class="app-w-350"
          clearable
        >
          <el-option label="全部人员" value />
          <el-option
            v-for="item in userListOptions"
            :key="item.id"
            :label="item.name+'（'+item.username+'）'"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <div>
        <el-form-item label=" ">
          <el-button type="primary" round @click="submitFilterForm">查询服务商</el-button>
          <el-button round @click="resetFilterForm">重置条件</el-button>
        </el-form-item>
      </div>

    </el-form>
    <!-- filter end -->

    <!-- 表格 start -->
    <div>
      <el-table :data="list" border stripe size="small">
        <el-table-column label="序号" type="index" align="center" width="60">
          <template slot-scope="scope">
            <span>{{ (paginationConfig.page - 1) * paginationConfig.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="服务商" />
        <el-table-column prop="serial" label="编号" />
        <el-table-column prop="username" label="账号" />
        <el-table-column label="权限组">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.spPackageDetail"
              type="primary"
            >{{ scope.row.spPackageDetail.name || '无' }}
            </el-tag>
            <el-tag v-else type="danger">无</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tags" label="标签">
          <template slot-scope="scope">
            <span v-if="scope.row.tags&&scope.row.tags.length">
              {{ scope.row.tags.join('、') }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="businessNum" label="商户数" width="80" />
        <el-table-column label="负责人" width="100">
          <template slot-scope="scope">
            <div>{{ scope.row.principal }}</div>
            <div>{{ scope.row.mobilePhone }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="creatorName" label="业务人员" />
        <el-table-column label="操作" width="50">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="jumpSpManage(scope.row)">管理</el-button>
          </template>
        </el-table-column>
      </el-table>
      <PaginationDirection
        v-if="paginationConfig.total!==0"
        :config="paginationConfig"
        @sizesChange="fetchData"
        @pageChange="fetchData"
      />
    </div>
    <!-- 表格 end -->

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { spPage } from '@/api/sp'
import { spPackageList } from '@/api/sp/package'
import { userList } from '@/api/user'
import { findMenuFirstChild } from '@/utils/menus'
import { tagList } from '@/api/sp/tag'

export default {
  props: {
    tabName: {
      type: String,
      default: 'search'
    }
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      spPackageOptions: [],
      tagOptions: [],
      userListOptions: [],
      // 状态
      loading: false,
      // 数据
      list: [],
      filterForm: {
        name: null,
        serial: null,
        userSuffix: null,
        spPackageId: null,
        tags: [],
        creator: null
      },
      allFilterIds: {
        tags: [] // 所有tags key
      },
      lastFilterIds: {
        tags: [] // 上次tags key
      }
    }
  },
  computed: {
    ...mapGetters(['sidebarMenus', 'activeSidebarMenusCode'])
  },
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {
    // if (this.tabName === 'spPage') {
    this.fetchUserList()
    this.fetchSpPackageList()
    this.fetchTagOptions()
    this.fetchData()
    // }
    this.$refs.filterFormInput && this.$refs.filterFormInput.focus()
  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
    // if (this.tabName === 'spPage' || this.tabName === 'searchSpPage' && this.list.length) {
    this.fetchUserList()
    this.fetchSpPackageList()
    this.fetchTagOptions()
    this.fetchData()
    // }
    this.$refs.filterFormInput && this.$refs.filterFormInput.focus()
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    /**
     * 数据组
     */
    // 获取列表
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 请求参数
      const params = Object.assign({}, this.filterForm)
      params.pageNum = page
      params.pageSize = pageSize
      // 清除多余字段
      params.tags = params.tags.includes('') ? [] : params.tags
      for (const key in params) {
        if (this.$isNull(params[key]) || Array.isArray(params[key]) && params[key].length === 0) delete params[key]
      }
      // 请求
      this.loading = true
      spPage({ data: params })
        .then(res => {
          this.list = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取权限组
    fetchSpPackageList() {
      spPackageList().then(res => {
        this.spPackageOptions = res.data || []
      }).finally(() => {
      })
    },

    // 获取列表
    fetchTagOptions() {
      tagList().then(res => {
        this.tagOptions = res.data || []
        this.allFilterIds.tags = [''].concat(this.tagOptions)
      }).finally(() => {
      })
    },

    // 获取用户
    fetchUserList() {
      userList({ data: { includeAdmin: true } }).then(res => {
        this.userListOptions = res.data || []
      }).finally(() => {
      })
    },

    /**
     * 按钮组
     */
    // 查询
    submitFilterForm() {
      this.fetchData(1)
    },

    // 重置
    resetFilterForm() {
      this.$refs.filterForm.resetFields()
    },

    // 打开服务商管理
    jumpSpManage(row) {
      this.$store.state.menus.activeSidebarMenusCode = 'Sp'
      this.$store.state.menus.sidebarMenusPrevPageCode = 'SystemSpManage'
      this.$store.state.menus.activeSidebarSpId = row.id
      this.$store.state.menus.activeSidebarSpInfo = {
        id: row.id,
        name: row.name
      }
      this.$router.push({
        name: findMenuFirstChild(this.sidebarMenus[this.activeSidebarMenusCode]).code,
        query: {
          spId: row.id
        }
      })
    },
    /**
     * 状态组
     */
    // 多选改变
    selectMultipleChange(val, type) {
      const lastVal = this.lastFilterIds[type]
      if (val.includes('')) {
        this.filterForm[type] = this.allFilterIds[type]
      }
      if (lastVal.includes('') && !val.includes('')) {
        this.filterForm[type] = []
      }
      if (lastVal.includes('') && val.includes('')) {
        val.splice(
          val.findIndex((v) => v === ''),
          1
        )
        this.filterForm[type] = val
      }
      if (!lastVal.includes('') && !val.includes('')) {
        if (val.length === this.allFilterIds[type].length - 1) {
          this.filterForm[type] = [''].concat(val)
        }
      }
      this.lastFilterIds[type] = this.filterForm[type]
    }
    /**
     * 方法组
     */

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.sp-page-main {
  margin-top: 10px;
}
</style>
